﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TL_Cloud.Core.Extensions;
using TL_Cloud.Core.Interfaces;
using TL_Cloud.Models.BookShop;
using TL_Cloud.RepositoryInterface.BookShop;
using TL_Cloud.ViewModels.BookShop.BaseTeachClass;

namespace TL_Cloud.API.Controllers
{

    /// <summary>
    /// 教师教学班级
    /// </summary>
    //[Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class TeachClassController:ControllerBase
    {
        private readonly ILogger logger;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IBaseTeachClassRepository _repository;
        private readonly IUrlHelper _urlHelper;

        public TeachClassController(
            ILogger<BKInfoController> logger,         
            IBaseTeachClassRepository repository,
            IUnitOfWork unitOfWork
            )
        {
            
            this.logger = logger;        
            this._repository = repository;
            this._unitOfWork = unitOfWork;
        }
        /// <summary>
        /// 获取所有的教学班级数据
        /// 搜索条件是:teacherId
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        [HttpGet(Name = "GetTeachClasses")]
        public async Task<IActionResult> Get([FromQuery]BaseTeachClassQueryParameters parameters)
        {

            var dataList = await _repository.GetAllEntitiesAsync(parameters);
 
            //数据返回分页数据
            var meta = new
            {
                dataList.TotalItemsCount,
                dataList.PageSize,
                dataList.PageIndex,
                dataList.PageCount, 
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));
            //返回结果塑性
            return Ok(dataList.ToDynamicIEnumerable(parameters.Fields));
        }

        ///// <summary>
        ///// 获取单个教学班级数据
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="fields"></param>
        ///// <returns></returns>
        //[HttpGet("{id}", Name = "GetTeachClass")]
        //public async Task<IActionResult> Get(string id, string fields = null)
        //{ 
        //    var entity = await _repository.GetEntityByIdAsync(id);
        //    if (entity == null)
        //    {
        //        return NotFound();
        //    } 
        //    var shapedentityResource = entity.ToDynamic(fields);
        //    var result = (IDictionary<string, object>)shapedentityResource;
        //    return Ok(result);
        //}

        /// <summary>
        /// 增加教师所教班级列表
        /// </summary> 
        /// <param name="teacherId">教师编号</param>
        /// <param name="classIds">班级编号列表,采用,进行分割</param>
        [HttpPost(Name = "CreateTeachClass")]
        public async Task<IActionResult> Post([FromBody]JObject jobj)// string teacherId, string classIds)
        {
            string teacherId = jobj["teacherId"].ToString();
            string classIds = jobj["classIds"].ToString();
            if (jobj["classIds"] == null)
            {
                return BadRequest();
            }
            if (jobj["teacherId"] == null)
            {
                return BadRequest();
            }            

            var lst = await _repository.GetAllEntitiesAsync(new BaseTeachClassQueryParameters { isPage = false, teacherId = teacherId });
            foreach (var item in lst)
            {
                _repository.Delete(item);
            }
            var userinfo = this.GetUserInfo();
            string[] cls = classIds.Split(',');
            foreach (var item in cls)
            {
                if (string.IsNullOrEmpty(item) == false)
                {
                    var entity = new Base_TeachClass();
                    entity.Create(userinfo.Item1, userinfo.Item2);
                    entity.TeacherId = teacherId;
                    entity.ClassId = item;
                    _repository.Add(entity);
                }
            }

            if (!await _unitOfWork.SaveAsync())
            {
                throw new Exception("Save Failed!");
            }

            return NoContent();
        }

        ///// <summary>
        ///// 修改数据
        ///// </summary>
        ///// <param name="id"></param>
        //[HttpPut("{id}", Name = "UpdateTeachClass")]
        //public async Task<IActionResult> Update(string id, [FromBody] Base_TeachClass updateResource)
        //{
        //    if (updateResource == null)
        //    {
        //        return BadRequest();
        //    }
             
        //    var entity = await _repository.GetEntityByIdAsync(id);
        //    if (entity == null)
        //    {
        //        return NotFound();
        //    } 
        //    var userinfo = this.GetUserInfo();
        //    entity.Modify(userinfo.Item1, userinfo.Item2);
        //    if (!await _unitOfWork.SaveAsync())
        //    {
        //        throw new Exception($"Updating entity {id} failed when saving.");
        //    }
        //    return NoContent();
        //}

        ///// <summary>
        ///// 删除数据
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpDelete("{id}", Name = "DeleteTeachClass")]
        //public async Task<IActionResult> Delete(string id)
        //{
        //    var post = await _repository.GetEntityByIdAsync(id);
        //    if (post == null)
        //    {
        //        return NotFound();
        //    }
        //    _repository.Delete(post);

        //    if (!await _unitOfWork.SaveAsync())
        //    {
        //        throw new Exception($"Deleting entity {id} failed when saving.");
        //    }

        //    return NoContent();
        //}
    }
}
